package com.zpy.SmartChargeStation.netty.server.handlers;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.Timer;
import java.util.TimerTask;

/**
 * description: 推送消息到小程序
 */

@Slf4j
public class ImoocWebSocketOutboundHandler extends ChannelOutboundHandlerAdapter {

    private Timer timer;

    @Override
    public void handlerAdded(
            ChannelHandlerContext ctx) throws Exception {

        log.info(">>>>>>创建定时任务");
        // 当处理器添加到管道时启动定时任务
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                String msg = "message from netty " + System.currentTimeMillis();
                ctx.writeAndFlush(new TextWebSocketFrame(msg));
                log.info(">>>>>>推送消息到小程序："+msg);
            }
        }, 0, 20000);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 当处理器从管道移除时停止定时任务
        if (timer != null) {
            timer.cancel();
            log.info(">>>>>>定时任务已移除");
        }
    }

}
